package interaction

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"project/controller"
	"project/mySql"
	"strconv"
	"time"
)

/**
 * @File : comment.go
 * @Description : 评论操作
 * @Author : 吴概
 * @Date : 2023/2/10
 */

// CommentActionResponse 评论操作的Response
type CommentActionResponse struct {
	controller.Response
	Comment controller.Comment `json:"comment"`
}

// CommentListResponse 获取评论列表的Response
type CommentListResponse struct {
	controller.Response
	CommentList []controller.Comment `json:"comment_list,omitempty"`
}

// CommentAction 进行评论操作
func CommentAction(c *gin.Context) {
	videoId, _ := strconv.ParseInt(c.Query("video_id"), 10, 64)
	current := mySql.GetUserByToken(c.Query("token"))
	actionType := controller.ParseInt(c.Query("action_type"))
	video := mySql.GetVideoById(videoId)
	if actionType == 1 {
		text := c.Query("comment_text")
		if len(text) >= 255 {
			c.JSON(http.StatusOK, controller.Response{StatusCode: 1, StatusMsg: "评论过长"})
		}
		comment := controller.Comment{
			User:    current,
			Content: text,
			VideoId: videoId,
			Time:    time.Now().Format("01-02 15:04:05"),
		}
		mySql.NewCommentData(comment)
		comment.Time = comment.Time[0:5] //按文档要求，只需返回 月-日
		c.JSON(http.StatusOK, CommentActionResponse{
			Response: controller.Response{StatusCode: 0},
			Comment:  comment,
		})
		video.CommentCount++
	}
	if actionType == 2 {
		commentId := controller.ParseInt(c.Query("comment_id"))
		comment := mySql.GetComment(commentId)
		comment.IsDelete = true
		mySql.SaveComment(comment)
		video.CommentCount--
	}
	mySql.SaveVideo(video)
}

// CommentList 获取评论列表
func CommentList(c *gin.Context) {
	videoId, _ := strconv.ParseInt(c.Query("video_id"), 10, 64)
	commentList := mySql.GetCommentList(videoId)
	sortCommentList(&commentList, 0, len(commentList))
	res := make([]controller.Comment, len(commentList))
	j := 0
	for i := range commentList {
		if commentList[i].IsDelete == true {
			continue
		}
		commentList[i].User = mySql.GetUser(commentList[i].UserId)
		commentList[i].Time = commentList[i].Time[0:5] //按文档要求，只需返回 月-日
		res[j] = commentList[i]
		j++
	}
	c.JSON(http.StatusOK, CommentListResponse{
		Response:    controller.Response{StatusCode: 0},
		CommentList: res,
	})
}

// 使用快速排序对评论列表排序，以评论时间排序，排序时精确到秒
func sortCommentList(list *[]controller.Comment, left, right int) {
	if left >= right {
		return
	}
	tempList := *list
	pivot, _ := time.Parse("01-02 15:04:05", tempList[left].Time)
	j := left
	for i := left; i < right; i++ {
		temp, _ := time.Parse("01-02 15:04:05", tempList[i].Time)
		if temp.Before(pivot) {
			j++
			tempList[j], tempList[i] = tempList[i], tempList[j]
		}
	}
	tempList[left], tempList[j] = tempList[j], tempList[left]
	sortCommentList(list, left, j)
	sortCommentList(list, j+1, j)
}
